

export class SimplPool<T> {
    private caches: Array<T> = [];
    private actives: Array<T> = [];

    /**
     * 创建回调
     */
    public createHandler!: () => T | null;

    /**
     * 显示回调
     */
    public showHandler!: (item: T) => void;

    /**
     * 隐藏回调
     */
    public hideHandler!: (item: T) => void;

    /**
     * 销毁回调
     */
    public destroyHandler!: (item: T) => void;

    public constructor(data?: any) {
        if (data) {
            this.createHandler = data.createHandler;
            this.showHandler = data.showHandler;
            this.hideHandler = data.hideHandler;
            this.destroyHandler = data.destroyHandler;
        }
    }

    /**
     * 生成一个对象
     * @returns 
     */
    public spawn(): T {
        let item: any;
        if (this.caches.length > 0) {
            let i = this.caches.length - 1;
            item = this.caches.splice(i, 1)[0];
        }
        else {
            if (this.createHandler) {
                item = this.createHandler();
            }
        }
        if (item) {
            this.actives.push(item);
            if (this.showHandler)
                this.showHandler(item);
        }
        return item;
    }

    /**
     * 回收一个对象一个对象
     * @returns 
     */
    public recycle(item: T | null) {
        if (!item)
            return;
        for (let i = 0; i < this.actives.length; ++i) {
            if (this.actives[i] == item) {
                this.actives.splice(i, 1);
                break;
            }
        }
        this.caches.push(item);
        if (this.hideHandler)
            this.hideHandler(item);
    }

    public recycleAll() {
        while (this.actives.length > 0) {
            this.recycle(this.actives[0]);
        }
    }

    /**
     * 销毁
     */
    public destroy() {
        if (this.destroyHandler) {
            for (let i = 0; i < this.actives.length; ++i) {
                let item = this.actives[i];
                this.destroyHandler(item);
            }
            for (let i = 0; i < this.caches.length; ++i) {
                let item = this.caches[i];
                this.destroyHandler(item);
            }
        }

        this.actives.splice(0, this.actives.length);
        this.caches.splice(0, this.caches.length);
    }

    /**
     * 激活的数量
     */
    public get activeCount(): number {
        return this.actives.length;
    }
}